package com.oak.designmode._07_proxyParttern.dynamicProxy;


import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;

import java.lang.reflect.Method;

/**
 * 动态代理类
 *
 * @ClassName: DynamicProxy
 * @Description  不指定具体代理的对象，继承InvocationHandler接口
 * @Author guoxy
 * @Date 2019/11/30
 * @Version 1.0
 */
public class DynamicProxyHandler implements InvocationHandler {

    /** 不指定具体代理的对象 */
    private Object object;

    public DynamicProxyHandler(final Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("JDK动态代理，监听开始！");
        Object result = method.invoke(object, args);
        System.out.println("JDK动态代理，监听结束！");
        return result;
    }


    public static BuyHouse newProxyInstance(BuyHouse target) {
        /**
         * ClassLoader loader:      指定当前目标对象使用的类加载器,获取加载器的方法是固定的
         * Class<?>[] interfaces:   被代理类的接口类型
         * InvocationHandler:       动态代理器，参数为被代理的类
         */
        return (BuyHouse) Proxy
                .newProxyInstance(DynamicProxyHandler.class.getClassLoader(),
                        new Class<?>[] { BuyHouse.class },
                        new DynamicProxyHandler(target));

    }

}
